import { restService } from "@/apis/rest"
import { useCrypto } from "@/hooks/useCrypto"
import { useLocalStorage } from "@/hooks/useLocalStorage"
import { RootState } from "@/store"
import { setState } from "@/utils/core"
import { formatDateTime } from "@/utils/dayjs"
import { ElMessage, ElMessageBox } from "element-plus"
import { Module } from "vuex"
import { ICamera, ICameraManagementActions, ICameraManagementGetter, ICameraManagementMutations, ICameraManagementState } from "./types"

const state: ICameraManagementState = {
    cameraList: [],
    cameraCount: 0,
    cameraListPageAndSize: {
        page: 1,
        size: 6
    },
    cameraForm: {
        name: "",
        host: "",
        port: '',
        username: "",
        password: "",
        location: "",
        createdAt: "",
        updatedAt: ""
    },
    cameraFields: [
        { label: "ID", prop: "_id", width: 70 },
        { label: "名称", prop: "name", width: 70 },
        { label: "地址", prop: "host", width: 70 },
        { label: '端口', prop: 'port', width: 70 },
        { label: "账号", prop: "username", width: 70 },
        { label: '密码', prop: 'password', width: 70 },
        { label: "地点", prop: "location", width: 70 },
        { label: "创建时间", prop: "createdAt", width: 70 },
        { label: "更新时间", prop: "updatedAt", width: 70 }
    ],
    cameraFormRules: {
        name: [
            { required: true, message: "请输入设备名", trigger: "blur" },
            { max: 6, message: "长度不得大于6个字符", trigger: "blur" }
        ],
        host: [
            { required: true, message: "请输入设备地址", trigger: "blur" },
        ],
        port: [
            { required: true, message: "请输入端口", trigger: "blur" },
        ],
        username: [
            { required: true, message: "请输入账号", trigger: "blur" },
            { max: 6, message: "长度不得大于6个字符", trigger: "blur" }
        ],
        password: [
            { required: true, message: "请输入密码", trigger: "blur" },
            { min: 6, message: "长度要大于等于6个字符", trigger: "blur" }
        ],
        location: [{ message: "请输入地点", trigger: "blur" }],
        createdAt: [{ message: "请选择创建时间", trigger: "blur", default: new Date() }],
        updatedAt: [{ message: "请选择更新时间", trigger: "blur", default: new Date() }]
    },
    cameraFormComponent: {
        formStatus: "添加",
        formPlaceholder: {
            name: "请输入摄像头名称",
            host: "请输入摄像头地址",
            port: "请输入端口",
            username: "请输入账号",
            password: "请输入密码",
            location: "请输入地点",
            createdAt: "请选择创建时间",
            updatedAt: "请选择更新时间"
        },
        formControl: {
            submit: {
                value: '提交',
                type: 'primary'
            },
            reset: {
                value: '重置',
                type: 'default'
            }
        }
    },
}

const actions: ICameraManagementActions = {
    deleteCamera: async ({ commit }, { camera, index }) => {
        ElMessageBox.confirm("此操作将永久删除该设备, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
        })
            .then(async () => commit("_deleteCamera", { camera, index }))
            .catch(() => ElMessage.info("已取消删除"))
    },
    submitCameraForm: async ({ commit, state }, { form, formStatus }) => {
        const cameraForm = {
            _id: form._id,
            name: form.name,
            host: form.host,
            port: form.port,
            username: form.username,
            password: form.password,
            location: form.location,
            createdAt: form.createdAt,
            updatedAt: form.updatedAt
        };
        const { encrypt } = useCrypto()
        cameraForm.host = encrypt(cameraForm.host)
        cameraForm.username = encrypt(cameraForm.username)
        cameraForm.password = encrypt(cameraForm.password)
        commit('_submitCameraForm', { cameraForm, formStatus })
        commit('_resetCameraForm')
    },
}

const mutations: ICameraManagementMutations = {
    _setState: (state: ICameraManagementState, { path, value }) => {
        setState(state, path, value);
    },
    _deleteCamera: async (state: ICameraManagementState, { camera, index }) => {
        const res = await restService("camera", { _id: camera._id }).del()
        if (res && !res.message) {
            state.cameraList.splice(index, 1)
            ElMessage.success(`"${res.name}"删除成功`)
            state.cameraCount--;
        }
    },
    _getAndSetCameraList: async (state: ICameraManagementState, cameraList: any[]) => {
        state.cameraList = await restService('camera').getList();
    },
    _getAndSetCameraCount: async (state: ICameraManagementState, cameraCount: number) => {
        const res = await restService('camera').getCount();
        if (res) {
            state.cameraCount = res.result;
        }

    },
    _getAndUpdateCameraList: async (state: ICameraManagementState, pageAndSize = {}) => {
        const { setLocalStorage } = useLocalStorage()
        pageAndSize['page'] = pageAndSize['page'] || state.cameraListPageAndSize;
        pageAndSize['pageSize'] = pageAndSize['pageSize'] || state.cameraListPageAndSize.size;
        const res = (await restService("camera", pageAndSize).getList()) as ICamera[] | any
        if (res && !res.message) {
            const { decrypt } = useCrypto()
            state.cameraList = res.map((item: ICamera) => {
                item.username && (item.username = decrypt(item.username))
                item.password && (item.password = decrypt(item.password))
                item.host && (item.host = decrypt(item.host))
                item.createdAt = formatDateTime(item.createdAt.toString());
                item.updatedAt = formatDateTime(item.updatedAt.toString());
                return item
            })
            state.cameraList = [...res]
            setLocalStorage("bishe-cameraList", state.cameraList)
        }
    },
    _resetCameraForm: (state: ICameraManagementState) => {
        state.cameraFormComponent.formStatus = "添加";
        Object.keys(state.cameraForm).forEach(key => state.cameraForm[key] = "")
    },
    _submitCameraForm: async (state: ICameraManagementState, { cameraForm, formStatus }) => {
        if (formStatus === '添加') {
            const res = await restService('camera', cameraForm).add();
            if (res && !res.message) {
                res.createdAt = formatDateTime(res.createdAt.toString());
                res.updatedAt = formatDateTime(res.updatedAt.toString());
                state.cameraList.unshift(res)
                state.cameraCount++
            }
        } else {
            const res = await restService('camera', cameraForm).update();
            if (res && !res.message) {
                res.createdAt = formatDateTime(res.createdAt.toString());
                res.updatedAt = formatDateTime(res.updatedAt.toString());
                const index = state.cameraList.findIndex((item: any) => item._id === res._id);
                state.cameraList.splice(index, 1, res);
            }
        }
    }
}
const getters: ICameraManagementGetter = {
    getCameraList: (state: ICameraManagementState) => {
        return state.cameraList;
    },
    getPage: (state: ICameraManagementState) => {
        return state.cameraListPageAndSize.page;
    },
    getSize: (state: ICameraManagementState) => {
        return state.cameraListPageAndSize.size;
    }
}

export const cameraManagement: Module<ICameraManagementState, RootState> = {
    namespaced: true,
    state,
    actions,
    mutations,
    getters,
}
